﻿<%@ WebHandler Language="C#" Class="Message" %>

using System;
using System.Web;
using System.Collections.Generic;

using EHSubmit.Logic;
using EHSubmit.Model;
using EHSubmit.Util;

/// <summary>
/// 本来用于取消息内容用，暂时无用（或许考虑获取收件人的消息）
/// </summary>
public class Message : BaseAjaxHandler
{
    protected override void Mapping()
    {
        
        OprationMap["page"] = "Paging";                       //为grid分页
        OprationMap["sc"] = "SearchContact";                  //查找联系人
        OprationMap["list_contact"] = "SearchContactList";    //按条件查找联系人获得列表
        OprationMap["msgRemove"] = "Delete";                  //将信息移到垃圾箱
        OprationMap["add"] = "Add";                           //消息发送
        OprationMap["msgViewed"] = "Update";                  //已阅消息的标记
    }

    /// <summary>
    /// 为grid分页
    /// </summary>
    public void Paging()
    {
        if (Validate(ERole.Student) || Validate(ERole.Teacher))      
        {
            MessageManager messageManager = new MessageManager();
            int start = Convert.ToInt32(Context.Request["start"]);
            int limit = Convert.ToInt32(Context.Request["limit"]);

            int pageIndex = start / limit + 1;

            string formType = Context.Request["formType"] as string;
            IList<EHSubmit.Model.Message> messageList = null;
            int totalCount = 0;
            switch (formType)
            {
                case "inbox":
                    {
                        string receiverID = CurrentUser.ID;
                        messageList = messageManager.GetMessages(receiverID, pageIndex,0);
                        totalCount = messageManager.GetMessagePageCount(receiverID,0);
                        break;
                    }
                case "outbox":
                    {
                        string senderID = CurrentUser.ID;
                        messageList = messageManager.GetMessages(senderID, pageIndex, 1);
                        totalCount = messageManager.GetMessagePageCount(senderID, 1);
                        break;
                    }
                case "trash":
                    {
                        string UID = CurrentUser.ID;
                        messageList = messageManager.GetMessages(UID, pageIndex, 2);
                        totalCount = messageManager.GetMessagePageCount(UID, 2);
                        break;
                    }
            }
            string jsonData = "{}";
            if (messageList.Count != 0)
            {
                jsonData = JsonHelper.Serialize(messageList);
            }

            IsSuccess = true;

            ResponseText = "{success:true,totalProperty:" + totalCount.ToString() + ",root:" + jsonData + "}";

            //string msgData;
            //string jsonData = string.Empty;
            ////-----根据消息的发件人ID集合，找到用户集合,并与消息数据整合成json数据
            //UserManager userManager = new UserManager();
            //string userData;
            //for (i = 0; i < 10; i++)  //
            //{
            //    User user = new User();
            //    user = userManager.GetUser(messageList[i].SenderID);
            //    userData = string.Format("Name:\"{0}\",RoleId:\"{1}\"", user.Name, user.RoleId);

            //    msgData = string.Format("ID:{0},SenderID:\"{1}\",Title:\"{2}\",RecvTime:{3}", messageList[i].ID, messageList[i].SenderID, messageList[i].Title, JsonHelper.Serialize(messageList[i].RecvTime));
            //    jsonData += "{" + userData + "," + msgData + "}";

            //    if (i != 9)
            //    {
            //        jsonData += ",";
            //    }
            //}

        }
        else
        {
            Message = "您没有权限执行此操作";
        }
    }

    /// <summary>
    /// 查找联系人
    /// </summary>
    public void SearchContact()
    {
        if (Validate(ERole.Student) || Validate(ERole.Teacher))
        {
            UserManager contactManager = new UserManager();
            User contact = new User();
            string UID = Context.Request["UID"].ToString();
            contact = contactManager.GetUser(UID);

            string jsonContact = JsonHelper.Serialize(contact);
            IsSuccess = true;
            ResponseText = "{success:true,contact:" + jsonContact + "}";  //必须返回json数据格式 ，success需要确定
        }
        else
        {
            Message = "您没有权限执行此操作";
        }
    }

    /// <summary>
    /// 按条件查找联系人获得列表
    /// </summary>
    public void SearchContactList()
    {
        if (Validate(ERole.Student) || Validate(ERole.Teacher))
        {
            int start = Convert.ToInt32(Context.Request["start"]);
            int limit = Convert.ToInt32(Context.Request["limit"]);
            string searchCondit = Context.Request["searchCondit"].ToString();
            string conditField = Context.Request["conditField"].ToString();
            if (conditField != null)
            {
                int pageIndex = start / limit + 1;

                UserManager contactManager = new UserManager();
                IList<User> contactList = contactManager.GetUsers(pageIndex, searchCondit, conditField);
                int totalCount = contactManager.GetUserPageCount(searchCondit, conditField);

                string jsonContacts = JsonHelper.Serialize(contactList);
                IsSuccess = true;
                ResponseText = "{success:true,totalProperty:" + totalCount.ToString() + ",root:" + jsonContacts + "}";  
		//据说返回{totalProperty:0,Data:'[]',Success:'true',success:'true'} 能解决bbar刷新残留上次数据问题
            }
            else
            {
                Message = "条件不看为空!";
            }
        }
        else
        {
            Message = "您没有权限执行此操作";
        }
    }

    /// <summary>
    /// 将信息删除
    /// </summary>
    public override void Delete()
    {
        if (Validate(ERole.Student) || Validate(ERole.Teacher))
        {
            string msgResult = string.Empty;
            
            MessageManager messageManager = new MessageManager();
            string gridID = Context.Request["gridID"].ToString();
            string msgID = Context.Request["msgID"].ToString();
            IList<string> msgIDList = JsonHelper.Deserialize<IList<string>>(msgID);
            switch (gridID)
            {
                case "inboxGrid":
                    {
                        messageManager.RDeleteMessages(msgIDList);
                        msgResult = "已经移到垃圾箱!";
                        break;
                    }
                case "outboxGrid":
                    {
                        messageManager.SDeleteMessages(msgIDList);
                        msgResult = "已经移到垃圾箱!";
                        break;
                    }
                case "trashGrid":
                    {
                        // 彻底删除指定的信息
                        DeleteCompletely(msgIDList);
                        msgResult = "已成功删除!";
                        break;
                    }
            }

            IsSuccess = true;
            ResponseText = "{success:true,msg:\"" + msgResult + "\"}";      //必须返回json数据格式 ，success需要确定
        }
        else
        {
            Message = "您没有权限执行此操作";
        }    
    }
    
    /// <summary>
    /// 彻底删除指定的信息
    /// </summary>
    private void DeleteCompletely(IList<string> msgIDList)
    {
        int i;
        IList<EHSubmit.Model.Message> msgList = new List<EHSubmit.Model.Message>();
        MessageManager messageManager = new MessageManager();
        EHSubmit.Model.Message message = null;
        msgList = messageManager.GetMessages(msgIDList);
        for (i = 0; i < msgList.Count; i++)
        {
            message = msgList[i];
            string msgID = message.ID.ToString();

            //-----特例：消息是自己发给自己的，且已经在发件箱和收件箱均做过删除，在数据库中作删除---------------------
            if (message.ReceiverID.Trim() == message.SenderID && message.IsSDeleted == 1 && message.IsRDeleted == 1)
            {
                messageManager.DeleleMessageReally(msgID);
            }
            //消息来自收件箱,对于消息来说当前用户为接收者,判断条件应该只要判断user的id即可,因为在垃圾箱的数据已经是从数据库筛选出的
            else if (message.ReceiverID.Trim() == CurrentUser.ID && message.IsRDeleted == 1)   //这里注意去掉空格
            {
                if (message.IsSDeleted == 2)         //消息发送方已经彻底删
                {
                    messageManager.DeleleMessageReally(msgID);
                }
                else
                {
                    messageManager.RDeleteMessage_Completely(msgID);
                }
            }
            //消息来自发件箱，对于消息来说当前用户为发件人，判断条件应该只要判断user的id即可,因为在垃圾箱的数据已经是从数据库筛选出的
            else   //message.SenderID == CurrentUser.ID AND message.IsSDeleted == 1  
            {
                if (message.IsRDeleted == 2)         //消息接收方已经彻底删
                {
                    messageManager.DeleleMessageReally(msgID);
                }
                else
                {
                    messageManager.SDeleteMessage_Completely(msgID);
                }

            }
        }
    }

    /// <summary>
    /// 发送消息，即添加消息入库
    /// </summary>
    public override void Add()
    {
        if (Validate(ERole.Student) || Validate(ERole.Teacher))
        {
            string msg = Context.Request["msg"].ToString();
            MessageManager messageManager = new MessageManager();
            //MID自增,SendTime.RecvTime要处理，IsViewed、IsSDeleted，IsSDeleted默认不处理
            EHSubmit.Model.Message message = JsonHelper.Deserialize<EHSubmit.Model.Message>(msg);
            message.Content = message.Content == null ? "" : message.Content;
            message.SendTime = DateTime.Now;
            message.RecvTime = DateTime.Now;
            
            messageManager.AddMessage(message);
            IsSuccess = true;
            ResponseText = "{success:true,msg:\"发送成功\"}";      //必须返回json数据格式 ，success需要确定
        }
        else
        {
            Message = "您没有权限执行此操作";
        }
    }

    /// <summary>
    /// 已阅信息的标记
    /// </summary>
    public override void Update()
    {
        if (Validate(ERole.Student) || Validate(ERole.Teacher))
        {
            MessageManager msgManager = new MessageManager();
            
            string msgIDRViewed = Context.Request["msgIDRViewed"].ToString();
            string msgIDSViewed = Context.Request["msgIDSViewed"].ToString();

            IList<string> msgIDRViewedList = JsonHelper.Deserialize<IList<string>>(msgIDRViewed);
            IList<string> msgIDSViewedList = JsonHelper.Deserialize<IList<string>>(msgIDSViewed);

            if (msgIDRViewedList != null)
            {
                msgManager.ViewMessage(msgIDRViewedList, true);
            }
            if (msgIDSViewedList != null)
            {
                msgManager.ViewMessage(msgIDSViewedList, false);
            }
            
            IsSuccess = true;
            ResponseText = "{success:true,msg:[]}";      //必须返回json数据格式 ，success需要确定
        }
        else
        {
            Message = "您没有权限执行此操作";
        }
    }
}